package com.example.juc.until;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
//自旋锁
public class ZiXuanLock {
    AtomicReference atomicReference =new AtomicReference();
    public  void myLock(){

        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"ok");
        //cas实现自旋锁
        while (!atomicReference.compareAndSet(null,thread)){

        }
    }
    public  void myunLock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(thread.getName()+"unlockok");
    }

    public static void main(String[] args) throws InterruptedException {
        ZiXuanLock z = new ZiXuanLock();
        //线程A没有释放锁 线程B会自旋4秒
        new Thread(() -> {
            z.myLock();
            try {
                TimeUnit.SECONDS.sleep(4);
            }catch (Exception e){
                e.getMessage();
            }finally {
                z.myunLock();
            }
        },"AA").start();


        TimeUnit.SECONDS.sleep(1);

        new Thread(() -> {
            z.myLock();
            try {
            }catch (Exception e){
                e.getMessage();
            }finally {
                z.myunLock();
            }
        },"BB").start();
    }
}
